﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;

using INSTA.StockApplication.DAL;
using INSTA.StockApplication.Library;

namespace INSTA.StockApplication.BLL
{
    public class Inventory
    {
        private ApplicationStockEntities _context = new ApplicationStockEntities();

        public Inventory()
        {
            
        }

        public List<ViewStock> GetStockFromDatabase()
        {
            return _context.ViewStocks.ToList();
        }

        public bool AddQuantityIntoDatabase(int idProduct, int quantite)
        {
            STOCK s = new STOCK();
            s.DATE_APPRO = System.DateTime.Today;
            s.ID_PRODUIT = idProduct;
            s.QUANTITE_RECUE = quantite;
            s.QUANTITE_RESTANTE = quantite;
            _context.Set<STOCK>().Add(s);
            return save(_context);
        }

        public void UpdateQuantityIntoDatabase(int idProduct , int quantite)
        {
            STOCK stock = _context.STOCKs.First(i => i.ID_PRODUIT == idProduct);
            stock.QUANTITE_RESTANTE = stock.QUANTITE_RESTANTE - quantite;
        }

        private static bool save(ApplicationStockEntities context)
        {
            try
            {
                context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                foreach (var s in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entite : {0} etat {1} : ", s.Entry.Entity.GetType().Name, s.Entry.State);
                    foreach (var v in s.ValidationErrors)
                    {
                        Console.WriteLine("Propriete {0}, erreur {1} : ", v.PropertyName, v.ErrorMessage);
                    }
                }
                return false;
            }
            return true;
        }
    }
}
